#ifndef CTCPCLIENT_H
#define CTCPCLIENT_H

/*
 * TCP 客户端通信类
*/
#include <QObject>
#include <QSemaphore>
#include <QMutex>

class QThread;
class QTcpSocket;
class CTcpClient : public QObject
{
    Q_OBJECT
public:
    explicit CTcpClient();
    ~CTcpClient();

    /* 连接服务器是否成功
     * 返回值 ： = true 已连接
     *         = false 未连接
    */
    bool IsConn() const;

	/* 连接服务器
     * @param:strServIp 服务器IP
     * @param:nSevPort 服务器端口号
    */
    bool ConnetServ(QString strServIp, quint16 nSevPort);

    /*向服务器发送数据
     * @param: data 发送数据内容
     * @param: maxSize 发送数据长度
     * 返回发送数据长度
    */
    qint64 Write(const char* data, qint64 maxSize = -1);

    // 断开与服务器连接
    void DisConn();


protected:
    //=======================
    QThread *m_pThread;
    QTcpSocket *m_pTcp;
    //=======================

    // write
    QMutex m_lockWrite;
    QSemaphore m_semWrite;
    QMutex m_lockWriteLen;
    qint64 m_iLen;

    //connect
    QMutex m_lockConnServ;
    QSemaphore m_semConnServ;
    bool m_isConn;

    //disconnect
    QMutex m_lockDisConn;
    QSemaphore m_semDisConn;

    //Buffer
    QByteArray m_readBuf;



signals:

    // 使用者可以connect 这个信号接收数据
    void sigDataReady(QByteArray);

    //=====================================================
    void sigDisConn();
    void sigConnetServ(const QString, const quint16);
    void sigWrite(const char *, qint64);

private slots:
    void slotDisConn();
    void slotConnetServ(const QString strServIP, const quint16 nServPort);
    void slotWrite(const char *pch, qint64);
    //======================================================
    void slotDataReady();

    void slotDisconnected();
};

#endif // CTCPCLIENT_H
